我們用三層架構來寫登入註冊
要先創建Controller、Service、Repository
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
@Tag(name = "身分驗證",description = "包含註冊、登出等身分驗證之API")
@Slf4j
public class AuthenticationController {
private final AuthenticationService service;
@Operation(summary = "註冊接口")
@PostMapping("/register")
public ResponseEntity<StatusResponse> register(
@RequestBody @Validated RegisterRequest request
){
return ResponseEntity.ok(service.register(request));
}
@Operation(summary = "登入接口")
@PostMapping("/login")
public ResponseEntity<AuthenticationResponse> login(
@RequestBody @Validated LoginRequest request
) {
return ResponseEntity.ok(service.login(request));
}
}
LoginRequest
RegisterRequest
StatusResponse為自訂義的回傳值,可以依自己喜好設計
AuthenticationResponse
身分認證後要將創建的token回傳
@Service
@Slf4j
@AllArgsConstructor
public class AuthenticationService {
private final AppUserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final JwtService jwtService;
/**
* 註冊
*/
public StatusResponse register(RegisterRequest request){
var user = AppUserEntity.builder()
.userName(request.getUserName())
.email(request.getEmail())
.password(passwordEncoder.encode(request.getPassword()))
.userRole(AppUserRole.USER)
.build();
userRepository.save(user);
return StatusResponse.builder()
.status("成功")
.build();
}
/**
* 登入
*/
public AuthenticationResponse login(LoginRequest request) {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
request.getEmail(),
request.getPassword()
)
);
var user = userRepository.findByEmail(request.getEmail()).orElseThrow();
var jwtToken = jwtService.generateToken(user);
log.info(jwtToken);
return AuthenticationResponse.builder()
.status("成功")
.token(jwtToken)
.build();
}
啟動Spring boot後,用Postmen測試
將要註冊的email與密碼打上去後Send
此時伺服器會回傳狀態為"成功"
然後到Spring boot查看內建之資料庫可以發現剛剛註冊的東西有成功丟進資料庫中
註冊完成後,就該來登入看看
把剛剛註冊的電子信箱與密碼打上去,這時候後端就會去驗證此用戶,若沒問題就會回傳token
這個token前端要幫忙存好以便後續想訪問登入與註冊以外的API
因為我在設定Security時只允許開頭為/api/auth之API可以不經授權訪問
當我們沒有帶token進去Security就會回傳401、403給客戶端
將登入給的token放上去就可以成功訪問了